package com.ysd.lis.controller.bac;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ysd.common.Result;
import com.ysd.lis.controller.pub.BaseController;
import com.ysd.lis.entity.SysInterface;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.bac.BacBloodCultrue;
import com.ysd.lis.entity.bac.BacPublisFirstReport;
import com.ysd.lis.entity.bac.BacTestResult;
import com.ysd.lis.entity.lab.LabMaininfo;
import com.ysd.lis.entity.lab.LabRptresult;
import com.ysd.lis.mapper.sys.SysInterfaceMapper;
import com.ysd.lis.request.SysParamFieldValueDto;
import com.ysd.lis.request.SysParamParam;
import com.ysd.lis.service.SysParamValueService;
import com.ysd.lis.service.bac.BacBloodCultrueService;
import com.ysd.lis.service.bac.BacPublisFirstReportService;
import com.ysd.lis.service.bac.BacTestResultService;
import com.ysd.lis.service.lab.LabMaininfoService;
import com.ysd.lis.service.lab.impl.LabMaininfoServiceImpl;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author cfz
 * @since 2024-08-27
 */
@RestController
@RequestMapping("/api/bac/bac-publis-first-report")
public class BacPublisFirstReportController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(BacPublisFirstReportController.class);

    @Autowired
    BacPublisFirstReportService bacPublisFirstReportService;
    @Autowired
    SysParamValueService sysParamValueService;
    @Autowired
    SysInterfaceMapper sysInterfaceMapper;
    @Autowired
    LabMaininfoService labMaininfoService;
    @Autowired
    BacTestResultService bacTestResultService;
    @Autowired
    BacBloodCultrueService bacBloodCultrueService;

    @ApiOperation("查询")
    @GetMapping("/findBacPublisFirstReportList")
    public Result findBacPublisFirstReportList(BacPublisFirstReport bacPublisFirstReport) {
        LambdaQueryWrapper<BacPublisFirstReport> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<BacPublisFirstReport> list = bacPublisFirstReportService.list(lambdaQueryWrapper);
        return Result.succ(1, "查询成功", list);
    }

    @ApiOperation("批量增加")
    @PostMapping("/batchSavePublisFirstReport")
    public Result batchSavePublisFirstReport(@RequestBody List<BacPublisFirstReport> bacPublisFirstReports) {
        boolean b = bacPublisFirstReportService.saveBatch(bacPublisFirstReports);
        if (b) {
            return Result.succ(1, "添加成功", "");
        }
        return Result.fail("添加失败");
    }


    @ApiOperation("批量修改")
    @PostMapping("/batchEditPublisFirstReport")
    public Result batchEditPublisFirstReport(@RequestBody List<BacPublisFirstReport> bacPublisFirstReports) throws JsonProcessingException {
        if (CollectionUtils.isNotEmpty(bacPublisFirstReports)) {
            LambdaQueryWrapper<BacPublisFirstReport> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            Timestamp timestamp = new Timestamp(bacPublisFirstReports.get(0).getSampleda().getTime());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = sdf.format(timestamp);
            Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
            Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
            lambdaQueryWrapper.ge(BacPublisFirstReport::getSampleda, startTime);
            lambdaQueryWrapper.le(BacPublisFirstReport::getSampleda, endTime);
            lambdaQueryWrapper.eq(BacPublisFirstReport::getRptGroup, bacPublisFirstReports.get(0).getRptGroup());
            lambdaQueryWrapper.eq(BacPublisFirstReport::getSampleNo, bacPublisFirstReports.get(0).getSampleNo());
            lambdaQueryWrapper.eq(BacPublisFirstReport::getTestFlowNo, bacPublisFirstReports.get(0).getTestFlowNo());
            lambdaQueryWrapper.eq(BacPublisFirstReport::getTestNodeNo, bacPublisFirstReports.get(0).getTestNodeNo());
            lambdaQueryWrapper.eq(BacPublisFirstReport::getCulMediumNo, bacPublisFirstReports.get(0).getCulMediumNo());
            bacPublisFirstReportService.remove(lambdaQueryWrapper);
        }
        boolean b = bacPublisFirstReportService.saveBatch(bacPublisFirstReports);
        //发布初级报告调用his接口
        if (CollectionUtils.isNotEmpty(bacPublisFirstReports)) {
            /*微生物发送一级二级报告回传his*/
            SysParamParam sysp1 = new SysParamParam();
            sysp1.setParamCode("xtxxcs");
            sysp1.setField("wswfsyjejbghchis");
            List<SysParamFieldValueDto> r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
            if (!r1.isEmpty()) {
                if (r1.get(0).getValue().equals("1")) {
                    //更新血培养表状态
                    LambdaUpdateWrapper<BacBloodCultrue> lambdaUpdateWrapper1 = new LambdaUpdateWrapper();
                    lambdaUpdateWrapper1.eq(BacBloodCultrue::getRptGroup, bacPublisFirstReports.get(0).getRptGroup())
                            .eq(BacBloodCultrue::getSampleNo, bacPublisFirstReports.get(0).getSampleNo())
                            .eq(BacBloodCultrue::getSampleda, bacPublisFirstReports.get(0).getSampleda())
                            .eq(BacBloodCultrue::getDelFlag, 0);
//                            .set(BacBloodCultrue::getBacPublishStatus, 1)
//                            .set(BacBloodCultrue::getResultTime, new Timestamp(System.currentTimeMillis()))
//                            .set(BacBloodCultrue::getResultThreeDays, null);
//                    bacBloodCultrueService.update(lambdaUpdateWrapper1);
                    List<BacBloodCultrue> bloodCultrueList = bacBloodCultrueService.list(lambdaUpdateWrapper1);
                    if(ToolsUtils.isNotEmpty(bloodCultrueList)){
                        for(BacBloodCultrue bloodCultrue : bloodCultrueList){
                            bloodCultrue.setBacPublishStatus(new BigDecimal(1));
                            bloodCultrue.setResultThreeDays(null);
                            if(ToolsUtils.isEmpty(bloodCultrue.getResultTime())){
                                bloodCultrue.setResultTime(new Timestamp(System.currentTimeMillis()));
                            }
                        }
                        bacBloodCultrueService.updateBatchById(bloodCultrueList);
                    }


                    SysUser sysUser = RedisUserManager.getUser();
                    LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(SysInterface::getDelFlag, 0);
                    wrapper.eq(SysInterface::getIsEnable, 1);
                    wrapper.eq(SysInterface::getOrgId, sysUser.getOrgId());
                    List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
                    List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
                    /*发布报告相关*/
                    for (String webUrl : collect) {
                        String releaseReport = webUrl + "/public/releaseWswReport";
                        List<Map> list = new ArrayList<>();
                        Map<String, Object> releaseReportMap = new HashMap<>();
                        HashMap<Object, Object> map1 = new HashMap<>();
                        map1.put("rptGroup", bacPublisFirstReports.get(0).getRptGroup());
                        map1.put("sampleNo", bacPublisFirstReports.get(0).getSampleNo());
                        map1.put("sampleda", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(bacPublisFirstReports.get(0).getSampleda()));
                        list.add(map1);
                        releaseReportMap.put("orgId", sysUser.getOrgId());
                        //子报告
                        releaseReportMap.put("children", "1");
                        releaseReportMap.put("reportInfos", list);
                        releaseReportMap.put("username", sysUser.getUsername());
                        releaseReportMap.put("realname", sysUser.getRealname());
                        String release = HttpUtil.createPost(releaseReport).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(releaseReportMap)).contentType("application/json").execute().body();
                        logger.info("微生物发布一级报告返回值:\n" + release);
                        JSONObject releaseObject = new JSONObject(release);
                        JSONObject releaseStatus = releaseObject.getJSONObject("status");
                        String releaseCode = releaseStatus.get("code").toString();
                        if (!"400".equals(releaseCode)) {
                            //更新主表状态
                            LambdaUpdateWrapper<LabMaininfo> lambdaUpdateWrapper = new LambdaUpdateWrapper();
                            lambdaUpdateWrapper.eq(LabMaininfo::getRptGroup, bacPublisFirstReports.get(0).getRptGroup())
                                    .eq(LabMaininfo::getSampleNo, bacPublisFirstReports.get(0).getSampleNo())
                                    .eq(LabMaininfo::getSampleda, bacPublisFirstReports.get(0).getSampleda())
                                    .eq(LabMaininfo::getDelFlag, 0)
                                    .set(LabMaininfo::getBacFlowNode, bacPublisFirstReports.get(0).getTestNodeNo());
                            labMaininfoService.update(lambdaUpdateWrapper);
                        }
                    }
                }
            }
        }
        if (b) {
            return Result.succ(1, "成功", "");
        }
        return Result.fail("失败");
    }
    @ApiOperation("初级报告撤销")
    @PostMapping("/batchCancelFirstReport")
    public Result batchCancelFirstReport(@RequestBody List<BacPublisFirstReport> bacPublisFirstReports) throws JsonProcessingException {
        if (CollectionUtils.isNotEmpty(bacPublisFirstReports)) {
            LambdaQueryWrapper<BacPublisFirstReport> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            Timestamp timestamp = new Timestamp(bacPublisFirstReports.get(0).getSampleda().getTime());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = sdf.format(timestamp);
            Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
            Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
            lambdaQueryWrapper.ge(BacPublisFirstReport::getSampleda, startTime);
            lambdaQueryWrapper.le(BacPublisFirstReport::getSampleda, endTime);
            lambdaQueryWrapper.eq(BacPublisFirstReport::getRptGroup, bacPublisFirstReports.get(0).getRptGroup());
            lambdaQueryWrapper.eq(BacPublisFirstReport::getSampleNo, bacPublisFirstReports.get(0).getSampleNo());
            lambdaQueryWrapper.eq(BacPublisFirstReport::getTestFlowNo, bacPublisFirstReports.get(0).getTestFlowNo());
            lambdaQueryWrapper.eq(BacPublisFirstReport::getTestNodeNo, bacPublisFirstReports.get(0).getTestNodeNo());
            lambdaQueryWrapper.eq(BacPublisFirstReport::getCulMediumNo, bacPublisFirstReports.get(0).getCulMediumNo());
            boolean remove = bacPublisFirstReportService.remove(lambdaQueryWrapper);
            //更新血培养状态
            LambdaUpdateWrapper<BacBloodCultrue> lambdaUpdateWrapper1 = new LambdaUpdateWrapper();
            lambdaUpdateWrapper1.eq(BacBloodCultrue::getRptGroup, bacPublisFirstReports.get(0).getRptGroup())
                    .eq(BacBloodCultrue::getSampleNo, bacPublisFirstReports.get(0).getSampleNo())
                    .eq(BacBloodCultrue::getSampleda, bacPublisFirstReports.get(0).getSampleda())
                    .eq(BacBloodCultrue::getDelFlag, 0)
                    .set(BacBloodCultrue::getBacPublishStatus, 0)
                    .set(BacBloodCultrue::getResultThreeDays, null);
            bacBloodCultrueService.update(lambdaUpdateWrapper1);
            if(remove){
                //把his的染色报告删除
                SysUser sysUser = RedisUserManager.getUser();
                LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(SysInterface::getDelFlag, 0);
                wrapper.eq(SysInterface::getIsEnable, 1);
                wrapper.eq(SysInterface::getOrgId, sysUser.getOrgId());
                List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
                List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
                //标本消申
                if (CollectionUtils.isNotEmpty(collect)) {
                    LambdaQueryWrapper<LabMaininfo> lambdaQueryWrapper111 = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper111
                            .eq(LabMaininfo::getRptGroup, bacPublisFirstReports.get(0).getRptGroup())
                            .eq(LabMaininfo::getSampleNo, bacPublisFirstReports.get(0).getSampleNo())
                            .eq(LabMaininfo::getSampleda, bacPublisFirstReports.get(0).getSampleda())
                            .eq(LabMaininfo::getDelFlag, 0);
                    LabMaininfo labMaininfo = labMaininfoService.getOne(lambdaQueryWrapper111);
                    //消审走报告发布传delete
                    for (String webUrl : collect) {
                        Map releaseReportMap1 = new HashMap();
                        String releaseReport1 = webUrl + "/public/releaseWswReport";
                        releaseReportMap1.put("orgId", sysUser.getOrgId());
                        releaseReportMap1.put("mainInfoId", labMaininfo.getId());
                        releaseReportMap1.put("deleteFlag", "1");
                        String release = HttpUtil.createPost(releaseReport1).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(releaseReportMap1)).contentType("application/json").execute().body();
                        logger.info("消审报告返回值:\n" + release);
                    }
                }
            }
        }
        return Result.succ(1, "成功", "");
    }

    @ApiOperation("获取历史报告")
    @PostMapping("/getBacPublisFirstReports")
    public Result getBacPublisFirstReports(@RequestBody BacPublisFirstReport bacPublisFirstReport) {
        return bacPublisFirstReportService.getBacPublisFirstReports(bacPublisFirstReport);
    }

    @ApiOperation("取消报告")
    @PostMapping("/cancelPublisFirstReport")
    public Result cancelPublisFirstReport(@RequestBody BacPublisFirstReport bacPublisFirstReport) {
        return bacPublisFirstReportService.cancelPublisFirstReport(bacPublisFirstReport);
    }

    @ApiOperation("删除报告")
    @PostMapping("/deletePublisFirstReport")
    public Result deletePublisFirstReport(@RequestBody BacPublisFirstReport bacPublisFirstReport) {
        return bacPublisFirstReportService.deletePublisFirstReport(bacPublisFirstReport);
    }

    @ApiOperation("发布细菌报告")
    @PostMapping("/publisGermReport")
    public Result publisGermReport(@RequestBody List<BacPublisFirstReport> bacPublisFirstReports) throws JsonProcessingException {
        //发布初级报告调用his接口
        if (CollectionUtils.isNotEmpty(bacPublisFirstReports)) {
            /*微生物发送一级二级报告回传his*/
            SysParamParam sysp1 = new SysParamParam();
            sysp1.setParamCode("xtxxcs");
            sysp1.setField("wswfsyjejbghchis");
            List<SysParamFieldValueDto> r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
            if (!r1.isEmpty()) {
                if (r1.get(0).getValue().equals("1")) {
                    //更新细菌结果表状态
                    LambdaUpdateWrapper<BacTestResult> lambdaUpdateWrapper1 = new LambdaUpdateWrapper();
                    lambdaUpdateWrapper1.eq(BacTestResult::getRptGroup, bacPublisFirstReports.get(0).getRptGroup())
                            .eq(BacTestResult::getSampleNo, bacPublisFirstReports.get(0).getSampleNo())
                            .eq(BacTestResult::getSampleda, bacPublisFirstReports.get(0).getSampleda())
                            .eq(BacTestResult::getDelFlag, 0)
                            .set(BacTestResult::getBacPublishStatus, 1);
                    bacTestResultService.update(lambdaUpdateWrapper1);

                    SysUser sysUser = RedisUserManager.getUser();
                    LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
                    wrapper.eq(SysInterface::getDelFlag, 0);
                    wrapper.eq(SysInterface::getIsEnable, 1);
                    wrapper.eq(SysInterface::getOrgId, sysUser.getOrgId());
                    List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
                    List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
                    /*发布报告相关*/
                    for (String webUrl : collect) {
                        String releaseReport = webUrl + "/public/releaseWswReport";
                        List<Map> list = new ArrayList<>();
                        Map<String, Object> releaseReportMap = new HashMap<>();
                        HashMap<Object, Object> map1 = new HashMap<>();
                        map1.put("rptGroup", bacPublisFirstReports.get(0).getRptGroup());
                        map1.put("sampleNo", bacPublisFirstReports.get(0).getSampleNo());
                        map1.put("sampleda", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(bacPublisFirstReports.get(0).getSampleda()));
                        list.add(map1);
                        releaseReportMap.put("orgId", sysUser.getOrgId());
                        //子报告
                        releaseReportMap.put("children", "1");
                        releaseReportMap.put("reportInfos", list);
                        releaseReportMap.put("username", sysUser.getUsername());
                        releaseReportMap.put("realname", sysUser.getRealname());
                        String release = HttpUtil.createPost(releaseReport).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(releaseReportMap)).contentType("application/json").execute().body();
                        logger.info("微生物发布一级报告返回值:\n" + release);
                        JSONObject releaseObject = new JSONObject(release);
                        JSONObject releaseStatus = releaseObject.getJSONObject("status");
                        String releaseCode = releaseStatus.get("code").toString();
                        if (!"400".equals(releaseCode)) {
                            //更新主表状态
                            LambdaUpdateWrapper<LabMaininfo> lambdaUpdateWrapper = new LambdaUpdateWrapper();
                            lambdaUpdateWrapper.eq(LabMaininfo::getRptGroup, bacPublisFirstReports.get(0).getRptGroup())
                                    .eq(LabMaininfo::getSampleNo, bacPublisFirstReports.get(0).getSampleNo())
                                    .eq(LabMaininfo::getSampleda, bacPublisFirstReports.get(0).getSampleda())
                                    .eq(LabMaininfo::getDelFlag, 0)
                                    .set(LabMaininfo::getBacFlowNode, bacPublisFirstReports.get(0).getTestNodeNo());
                            labMaininfoService.update(lambdaUpdateWrapper);
                            return Result.succ(1, "成功", "");
                        }
                    }
                }
            }
        }
        return Result.fail("失败");
    }


}
